<template>
    <div>
        <div class="sengContent">
            <span class="title">{{messageTitle}}</span>
            <el-button size="small" type="primary" @click="returnTable">返回</el-button>
        </div>
        <div class="basicInfo">
            <el-form :model="formInfo" ref="basicForm"  class="demo-ruleForm">
                 <el-form-item label="消息类型：" prop="type" label-width="120px"
                    :rules="[{required:true,message:'请选择消息类型',trigger:'blur'}]">
                    <el-select v-model="formInfo.type" placeholder="请选择消息类型" style="width:100%;" :disabled="detailsMessage">
                        <el-option
                            v-for="(item,index) of messageTypeList"
                            :key="index"
                            :label="item.text"
                            :value="parseInt(item.value)"
                        ></el-option>
                    </el-select>
                </el-form-item>
                 <el-form-item label="通知方式：" prop="receiveMode" :rules="[{required:true,message:'请选择通知方式',trigger:'blur'}]" label-width="120px">
                    <el-checkbox-group v-model="formInfo.receiveMode" :disabled="detailsMessage">
                        <el-checkbox :label="1">站内信</el-checkbox>
                        <el-checkbox :label="2">邮件</el-checkbox>
                        <el-checkbox :label="3">短信</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                 <el-form-item label="接收者：" prop="recipientFilterType" label-width="120px">
                    <el-radio-group v-model="formInfo.recipientFilterType" @change="changeRecipient" :disabled="detailsMessage"> <!--选择全部的时候 没有搜索框  -->
                        <el-radio :label="1">全部</el-radio>
                        <el-radio :label="2">用户</el-radio>
                        <el-radio :label="3">部门</el-radio>
                        <el-radio :label="4">角色</el-radio>
                        <el-radio :label="5">岗位</el-radio>
                    </el-radio-group>
                </el-form-item>
                 <el-form-item label="" prop="tykkpe" v-show="formInfo.recipientFilterType != 1" label-width="120px">
                    <div class="selectStyle">
                        <div class="inputSelect">
                            <el-tag
                                v-for="tag in tagsList"
                                :key="tag.id">
                                {{formInfo.recipientFilterType == 2 ? tag.username : tag.name }}
                            </el-tag>
                        </div>
                        <el-button  type="primary" @click="onRecipient" :disabled="detailsMessage" style="height: 36px">选择</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="消息标题：" prop="title" :rules="[{required:true,message:'请输入消息标题',trigger:'blur'}]" label-width="120px">
                    <el-input v-model="formInfo.title" placeholder="请输入消息标题"  :disabled="detailsMessage"></el-input>
                </el-form-item>
                 <el-form-item v-if="formInfo.receiveMode &&formInfo.receiveMode.indexOf(3) > 0" label="短信内容：" prop="smsContent" :rules="[{required:true,message:'请输入短信内容',trigger:'blur'}]" label-width="120px">
                    <el-input type="textarea" v-model="formInfo.smsContent" placeholder="请输入短信内容，限制75个字" :autosize="{ minRows: 2, maxRows: 4 }"  maxlength="75"></el-input>
                </el-form-item>
                 <el-form-item label="消息内容：" prop="content" :rules="[{required:true,message:'请输入消息内容',trigger:'blur'}]" label-width="120px">
                    <wangEditor  v-model="formInfo.content" :height="300" v-if="!detailsMessage" placeholder="在这里输入文字"  v-show="detailsMessage == true ? false : true"  ref="editorForm" />
                     <wangEditor v-model="formInfo.content" :height="300" v-if="detailsMessage" :readonly="true"  ref="editorForm" />
                </el-form-item>
                <el-form-item label="附件：" label-width="120px">
                    <el-upload
                        ref="fileUpload"
                        class="upload-demo"
                        :before-upload="beforeUpload"
                        :on-success="uploadSuccess"
                        :limit="5"
                        :multiple="true"
                        :on-exceed="onExceed"
                        :headers="{ 'Authorization': 'Bearer ' + localStorageTemp, 'tenant-id': tenantId }"
                        :show-file-list="false"
                        :action="loadAction"
                        :disabled="detailsMessage">
                        <el-button  type="primary" style="width: 200px" v-loading="uploadLoading">文件上传</el-button>
                        <div slot="tip" class="el-upload__tip">
                            <span>提示：最多上传5个文件，单个文件不超过10M。</span>
                            <div v-if="fileDocList.length > 0" class="showFileDoc">
                                <div class="lineFilecss" v-for="(item, idx) in fileDocList" :key="idx">
                                    <i class="el-icon-document"></i>
                                    <span class="fileTextCss" :title="item.name" @click="viewFile(item)">{{item.name}}</span>
                                    <span><i class="el-icon-download fileIcon" @click="downloadFileFunc(item)"></i></span>
                                    <span><i class="el-icon-delete fileIcon" @click="deleteFile(item, idx)"></i></span>
                                </div>
                            </div>
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="发送状态：" prop="sendAction" :rules="[{required:true,message:'请选择发送状态',trigger:'blur'}]" label-width="120px">
                    <el-radio-group v-model="formInfo.sendAction" :disabled="detailsMessage">
                        <el-radio :label="0">草稿</el-radio>
                        <el-radio :label="1">立即发送</el-radio>
                        <el-radio :label="2">定时发送</el-radio>
                    </el-radio-group>
                </el-form-item>
                 <el-form-item label="选择时间：" prop="sendTime" :rules="[{required:true,message:'请选择发送时间',trigger:'blur'}]" v-if="formInfo.sendAction == 2" label-width="120px">
                     <el-date-picker
                        :disabled="detailsMessage"
                        v-model="formInfo.sendTime"
                        type="datetime"
                        placeholder="选择日期时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item class="center" v-if="detailsMessage == true ? false : true">
                    <el-button type="primary" @click="onSubmit" :disabled="disButton">确定</el-button>
                    <el-button  @click="returnTable">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 选择用户 -->
        <ChoiceUser  ref="getUser" @userInfo="info" :tagsList="tagsList"  v-if="openRecipient" @closeRecipient="closeRecipient"/>
        <ChoiceDepartment ref='getDepartmen' @departmenInfo="info" :tagsList="tagsList"/>
        <ChoiceRole ref='getRole' @roleInfo="info" :tagsList="tagsList" v-if="openRole" @closeRole="closeRole"/>
        <ChoicePost ref='getPost' @postInfo="info" :tagsList="tagsList" @closePost="closePost" v-if="openPost"/>
    </div>
</template>
<script>
import WangEditor from '@/components/wangEdito/index.vue'
import Tinymce from '@/components/tinymce/index.vue'
import ChoiceUser from '@/components/selectUser/index.vue'
import ChoiceDepartment from '@/components/choiceDepartment/index.vue'
import ChoiceRole from '@/components/choiceRole/index.vue'
import ChoicePost from '@/components/choicePost/index.vue'
import { creatAnnouncement, updateAnnouncement} from '@/api/custom/message'
import { download } from '@/utils/index'
export default {
    components: {
        Tinymce,
        ChoiceUser,
        ChoiceDepartment,
        ChoiceRole,
        ChoicePost,
        WangEditor
    },
    props: {
        messageTitle: String,
        detailsMessage: Boolean,
        messageTypeList: Array,
        editList: {
            type: Object
        },
    },
    data() {
        return {
            disButton: false,
            tagsList: [],
            title: '',
            id: '',
            openPost: false,
            openRole: false,
            openRecipient: false,
            formInfo:{
                type: '',
                recipientFilterType: 1,
                receiveMode: [ 1 ],
                sendAction: 0,
                sendTime: '',
                content: '',
                title: '',
                smsContent: ''
            },
            localStorageTemp: '',
            tenantId: '',
            loadAction: '',
            api: '',
            uploadLoading: false,
            fileDocList: [],
        }
    },
    created () {
        this.api = process.env.VUE_APP_BASE_API;
        this.loadAction = `${this.api}/admin-api/infra/file/upload`;
        this.localStorageTemp = window.localStorage.getItem('ACCESS_TOKEN');
        this.tenantId = window.localStorage.getItem('TENANT_ID')
        if(this.messageTitle == '发送新消息'){
            this.getData(this.formInfo)
        }else{
            this.getData(this.editList)
        }
    },
    methods: {
        getData(newVal) {
            this.formInfo = JSON.parse(JSON.stringify(newVal))
            if(newVal.recipientFilterCondition){
                this.tagsList = JSON.parse(JSON.stringify(newVal.recipientFilterCondition))
            }else{
                this.tagsList = []
            }
            if(newVal.allFileList) {
                this.fileDocList = JSON.parse(newVal.allFileList) || []
            }else{
                this.fileDocList = []
            }
            this.id = newVal.id
        },
        viewFile (item) {
            const nameSplitList = item.name.split('.')
            const type = nameSplitList[nameSplitList.length - 1]
            if (['jpeg', 'jpg', 'png'].includes(type)) {
                window.open(item.url, '_blank')
            } else {
                this.$message.warning('当前文件不支持预览')
            }
            // 代码注释
            //  else if (['docx', 'doc', 'xlsx', 'xls', 'pdf'].includes(type)) {
            //     this.$message.warning('当前文件不支持预览')
            //     // let newFileUrl = encodeURIComponent(item.url)
            //     // newFileUrl = 'http://view.xdocin.com/xdoc?_xdoc=' + newFileUrl
            //     // window.open(newFileUrl, '_blank')
            // } else if (type === 'pdf') {
            //     this.$message.warning('当前文件不支持预览')
            // }
        },
        downloadFileFunc (item) {
            download(item.url, item.name)
        },
        deleteFile (item, idx) {
            if(!detailsMessage){
              this.fileDocList.splice(idx, 1)
            }
        },
        onExceed (files, fileList) {
            if (this.fileDocList.length === 5) {
                this.$message.warning('当前限制5个文件')
                this.$refs.fileUpload.abort()
                return false
            }
        },
        // 上传前钩子判断
        beforeUpload (file) {
            const size = file.size / 1024 / 1024
            if (size > 10) {
                this.$message.warning('文件最大不超过10M')
                return false
            }
            this.uploadLoading = true
        },
        // 上传成功钩子事件
        uploadSuccess (response, file, fileList) {
            if (response.code === 0) {
                this.fileDocList.push({
                    url: response.data,
                    name: file.name 
                })
            }
            this.uploadLoading = false
        },
        onSubmit() {
            if(this.formInfo.recipientFilterType != 1 && this.tagsList.length == 0){
                this.$message.warning('请先选择接收者')
                return
            }
            this.$refs.basicForm.validate((validate) => {
                if(validate){
                    let dataText = this.$refs.editorForm.editor.txt.html().replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, '[图片]')
                    dataText = dataText.replace(/<video [^>]*src=['"]([^'"]+)[^>]*>/gi, '[视频]')
                    dataText = dataText.replace(/<\/?.+?\/?>/g, '')
                    this.disButton = true
                    const text = this.$refs.editorForm.editor.txt.text()// 获取富文本中的纯文字
                    const date = this.formInfo.sendTime
                    if(date && date instanceof Object ) {
                        this.formInfo.sendTime = parseInt(Date.parse(this.formInfo && this.formInfo.sendTime))
                    }
                    // 新增附件功能 
                    this.formInfo.allFileList = JSON.stringify([...this.fileDocList])
                    let arr = []
                    this.tagsList && this.tagsList.map((_) => {
                        arr.push(_.id)
                    })
                    const data = {...this.formInfo,recipientFilterCondition: arr,contentDisplay: dataText}
                    if(this.messageTitle == '发送新消息'){
                        creatAnnouncement(data).then((res) => {
                            if(res.code === 0){
                                this.fileDocList = []
                                this.$emit("saveMessage")
                            }
                        })
                        .finally(() => {
                            setTimeout(() => {
                                this.disButton = false;
                            }, 2000)
                        });
                    }else{
                        data.id = this.id
                        updateAnnouncement(data).then((res) => {
                            if(res.code === 0){
                                this.fileDocList = []
                                this.$emit("saveMessage")
                            }
                        }).finally(() => {
                            setTimeout(() => {
                                this.disButton = false;
                            }, 2000)
                        });
                    }
                }
            })
        },
        returnTable() {
            this.$emit("returnTable")
            this.tagsList = []
            this.$refs.basicForm.resetFields()
        },
        onRecipient() {
            if(this.formInfo.recipientFilterType === 2){ // 用户选择
                this.openRecipient = true
            }else if(this.formInfo.recipientFilterType === 3){ //选择部门
                this.$refs.getDepartmen.init()
            }else if(this.formInfo.recipientFilterType === 4){ //选择角色
                this.openRole = true
            }else if(this.formInfo.recipientFilterType === 5){ //选择岗位
                this.openPost = true
            }
        },
        changeRecipient() {
            this.tagsList = []
        },
        info(data) {
            this.tagsList = data
        },
        closePost() {
            this.openPost = false
        },
        closeRole() {
            this.openRole = false
        },
        closeRecipient() {
             this.openRecipient = false
        }
    }
}
</script>
<style lang="scss" scoped>
.lineFilecss{
    padding: 3px 0;
}
.showFileDoc{
    padding: 10px 0;
}
.fileTextCss{
    cursor: pointer;
    width: 45%;
    padding: 0 10px;
    display: inline-block;
    vertical-align: text-bottom;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    &:hover {
        color: #409EFF;
    }
}
.fileIcon{
    padding: 0 5px;
    cursor: pointer;
    &:hover {
        color: #409EFF;
    }
}
.sengContent{
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.title{
    color: rgb(64, 158, 255);
    font-size: 16px;
}
.basicInfo {
    margin-right: 20%;
    margin-left: 20%;
    margin-top: 3%;
}
.center{
    text-align: center;
}
.selectStyle{
    display: flex;
    width: 100%;
}
.inputSelect{
    width: 100%;
    height: 36px;
    line-height: 2.3;
    background-color: #FFFFFF;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    padding: 0 15px;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: inherit;
}
.selectStyle .el-tag+.el-tag{
    margin-left: 10px;
} 
.messageContent {
    display: flex;
    align-items: center;
}
    .messageContent  ::v-deep .el-form-item__label{
    width: 120px;
}
</style>
